package com.itheima.jdbctemplate;

import com.itheima.domain.Emp;
import com.itheima.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JdbcTemplateDemo02 {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Test
    public void test1() {
        String sql = "update account set balance=10000 where id=?";
        int count = template.update(sql, 1);
        System.out.println(count);
    }

    @Test
    public void test2() {
        String sql = "insert into account values (?,?,?)";
        int count = template.update(sql, 4, "郭靖", 2000);
        System.out.println(count);
    }

    @Test
    public void test3() {
        String sql = "delete from account where id=?";
        int count = template.update(sql, 4);
        System.out.println(count);
    }

    @Test
    public void test4() {
        String sql = "select * from account where id=?";
        Map<String, Object> map = template.queryForMap(sql, 1);
        System.out.println(map);
    }

    @Test
    public void test5() {
        String sql = "select * from account";
        List<Map<String, Object>> list = template.queryForList(sql);
        System.out.println(list);
    }

    @Test
    public void test6_1() {
        String sql = "select * from account";
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {
            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp = new Emp();
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int balance = rs.getInt("balance");
                emp.setId(id);
                emp.setName(name);
                emp.setBalance(balance);
                return emp;
            }
        });
        System.out.println(list);
    }

    @Test
    public void test6_2() {
        String sql = "select * from account";
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        System.out.println(list);
    }

    @Test
    public void test7() {
        String sql = "select COUNT(id) from account";
        Long total = template.queryForObject(sql, long.class);
        System.out.println(total);
    }
}
